import { createRouter, createWebHashHistory, createWebHistory, type Router, type RouteRecordRaw } from "vue-router";

// 2. 配置路由
const defaultRoutes: RouteRecordRaw[] = [
  {
    path: "/hello",

    component: () => import("./components/Hello.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("./components/Login.vue"),
  },
  {
    path: "/",
    component: () => import("./components/Login.vue"),
  },
  {
    path: "/reg",
    name: "reg",
    component: () => import("./components/Reg.vue"),
  },
  {
    path: "/index",
    name: "index",
    component: () => import("./components/Index.vue"),
    meta: {
      requiresAuth: true,
    }
  },
]



// 1.返回一个 router 实列，为函数，里面有配置项（对象） history
export const router:Router = createRouter({
  history: createWebHistory(),
  routes: defaultRoutes,
});
 
// 3导出路由   然后去 main.ts 注册 router.ts'

router.beforeEach((to, from) => {
  const token = localStorage.getItem('token');
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    // 需要登录验证的页面
    if (token) {
      // 已登录，继续访问
    } else {
      // 未登录，重定向到登录页面
    return { name: 'login' }
    }
  } else {
    // 不需要登录验证的页面
  }
});